using Dapper;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.ArrivalInspection;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ArrivalInspection;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace RBAC.Write.Api.Application.Handler.ArrivalInspection
{
    /// <summary>
    /// 删除到货检验（软删除主表，物理删除子表）
    /// </summary>
    public class DeleteArrivalInspectionHandler : IRequestHandler<DeleteArrivalInspectionCommand, APIResult<long>>
    {
        private readonly IBaseRepository<ArrivalInspectionInfo> _headerRepo;
        private readonly IDbConnectionFactory _connectionFactory;
        private readonly ILogger<DeleteArrivalInspectionHandler> _logger;

        public DeleteArrivalInspectionHandler(
            IBaseRepository<ArrivalInspectionInfo> headerRepo,
            IDbConnectionFactory connectionFactory,
            ILogger<DeleteArrivalInspectionHandler> logger)
        {
            _headerRepo = headerRepo;
            _connectionFactory = connectionFactory;
            _logger = logger;
        }

        public Task<APIResult<long>> Handle(DeleteArrivalInspectionCommand request, CancellationToken cancellationToken)
        {
            var res = new APIResult<long>();
            try
            {
                if (request == null || request.Id <= 0)
                {
                    res.Code = APIEnums.Fail;
                    res.Msg = "参数错误";
                    return Task.FromResult(res);
                }

                var exists = _headerRepo.QueryFirstOrDefault<int>(
                    "SELECT COUNT(1) FROM ArrivalInspectionInfo WHERE Id = @Id AND IsDeleted = 0",
                    new { request.Id });
                if (exists == 0)
                {
                    res.Code = APIEnums.Fail;
                    res.Msg = "记录不存在或已删除";
                    return Task.FromResult(res);
                }

                using (var conn = _connectionFactory.CreateConnectionWithRetry())
                using (var tran = conn.BeginTransaction())
                {
                    try
                    {
                        // 软删除主表
                        conn.Execute("UPDATE ArrivalInspectionInfo SET IsDeleted = 1 WHERE Id = @Id AND IsDeleted = 0;", new { request.Id }, tran);
                        // 物理删除子表
                        conn.Execute("DELETE FROM ArrivalInspectionItem WHERE InspectionId = @InspectionId;", new { InspectionId = request.Id }, tran);
                        conn.Execute("DELETE FROM ArrivalInspectionAttachment WHERE InspectionId = @InspectionId;", new { InspectionId = request.Id }, tran);

                        tran.Commit();
                    }
                    catch
                    {
                        try { tran.Rollback(); } catch { }
                        throw;
                    }
                }

                res.Code = APIEnums.Success;
                res.Msg = "删除成功";
                res.Data = request.Id;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "删除到货检验失败: {Message}", ex.Message);
                res.Code = APIEnums.Error;
                res.Msg = "删除到货检验失败";
            }
            return Task.FromResult(res);
        }
    }
}
